package com.water.wfo.component.api.config;

import com.alibaba.fastjson.JSONObject;
import com.water.wfo.component.constant.HttpApiConstants;
import com.water.wfo.component.spring.util.HttpUtils;
import com.water.wfo.component.util.StringUtil;
import com.water.wfo.component.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Order(0)
@Aspect
@Component
public class ApiAspect {

    @Autowired(required = false)
    private HttpServletRequest request;
    @Pointcut("execution(* com.water.wfo.*.controller.*Controller.*(..))")
    public void pointCut() {

    }

    @Around(value = "pointCut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        // 获取目标参数
        String serviceUniqueName = proceedingJoinPoint.getSignature().getDeclaringTypeName();
        String methodName = proceedingJoinPoint.getSignature().getName();
        long start = System.currentTimeMillis();
        Object proceed = proceedingJoinPoint.proceed();
        String id = UUIDUtils.getUuid();
        String clientIp = null;
        try{
            clientIp = HttpUtils.getUserClientIp();
        }catch (Exception e){
            log.error("获取客户端ip失败", e);
        }
        String url ="";
        String userAgent = "";
        if(null != request) {
            url = request.getRequestURI();
            // user-agent
            userAgent = request.getHeader(HttpApiConstants.USER_AGENT);
        }
        StringBuilder paramBuilder = new StringBuilder();
        for(Object arg : proceedingJoinPoint.getArgs()){
            paramBuilder.append(getParamStr(arg));
            paramBuilder.append(",");
        }
        log.info("request id: {},clientIp:{},url:{},time:{},{},请求参数:{}", id, clientIp, url, start, userAgent, paramBuilder);
        log.info("serviceName:{}.{},耗时:{}ms", serviceUniqueName, methodName,
                System.currentTimeMillis() - start);
        return proceed;
    }

    /**
     * 请求参数
     * @param arg
     * @return
     */
    private String getParamStr(Object arg){
        if(null == arg) {
            return null;
        }else if(StringUtil.isBlank(arg)) {
            return "";
        }
        return JSONObject.toJSONString(arg);
    }
}
